package com.paul.mq.service.impl.mqtt;

import com.paul.mq.bean.dto.AliMQTTDTO;
import com.paul.mq.bean.enums.MQTTEnum;
import com.paul.mq.bean.vo.AliyunMQTTVO;
import com.paul.mq.config.AliyunMQTTConfig;
import com.paul.mq.service.IMQTTService;
import com.paul.mq.service.MQTTServiceFactory;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author ZMK
 * @date 2022/1/27 15:33
 * @description
 */
@Service("MQTTAliyunServiceImpl")
public class AliyunServiceImpl implements IMQTTService, InitializingBean {

    private static final Logger logger = LoggerFactory.getLogger(AliyunServiceImpl.class);

    @Autowired
    private AliyunMQTTConfig mqttConfig;

    @Autowired
    private MqttClient mqttClient;

    @Override
    public String send() {
        logger.info("AliyunServiceImpl=>send");
        return this.getType();
    }

    @Override
    public String getType() {
        return MQTTEnum.ALIYUN_MQTT.toString();
    }

    @Override
    public AliyunMQTTVO SendMsg(AliMQTTDTO aliMQTTDTO) {
        return null;
//        try {
//            String sendMSg = "send mqtt: message body is :" + JSON.toJSONString(aliMQTTDTO);
//            logger.info(sendMSg);
//            String recvClientId = mqttConfig.getAliyunMQTTGroupId() + "@@@" + aliMQTTDTO.getTerminalNo();//+ config.getAliyunMQTTRecv();
//            final String p2pSendTopic = (StringUtils.isBlank(aliMQTTDTO.getTopic()) ? mqttConfig.getAliyunMQTTTopic() : aliMQTTDTO.getTopic()) + "/p2p/" + recvClientId;
//            MqttMessage mqttMessage = new MqttMessage(aliMQTTDTO.getBody().getBytes());
//            mqttMessage.setQos(mqttConfig.getAliyunMQTTQosLevel());
//            logger.info("send mqtt Topic：" + p2pSendTopic);
//            mqttClient.getTopic(p2pSendTopic).publish(mqttMessage);
//
//            return new AliyunMQTTVO(p2pSendTopic, String.valueOf(mqttMessage.getId()));
//        } catch (Exception ex) {
//            throw new BusinessException(ExceptionCode.DATA_NOT_FOUND.value(), ex.getMessage());
//        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        MQTTServiceFactory.register(MQTTEnum.ALIYUN_MQTT, this);
    }
}
